<?php
/**
 * ToplistController.php
 */

require_once 'ToplistModel.php';
require_once 'ToplistView.php';

/**
 * Displays MOVIEmeter top-10 movies of the week with some facebook interaction.
 */
class ToplistController {
	private $toplistModel;
	private $toplistView;

	public function __construct() {
		$this->toplistModel = new ToplistModel();
		$this->toplistView = new ToplistView();
	}

	public function doControll() {
		$html = '';

		// Get top 10 movies of the week list.
		require_once 'ImdbScraper.php';
		$imdbScraper = new ImdbScraper();
		$toplist = $this->toplistView->doToplist( $imdbScraper->getTop10Data() );

		if ( $this->toplistView->isCanvas() ) {
			$html .= $toplist;
		} else {
			// Connect application to Facebook.
			require_once 'facebook-sdk/src/facebook.php';
			$fb = new Facebook( array( 'appId' => '116424021804563', 'secret' => 'beb12765b63607bd6aa83f6c8ebfbe1f' ) );

			// Check if user is logged in with Facebook.
			$fbUser = $fb->getUser();
			if ( $fbUser ) {
				try {
					$fbProfile = $fb->api( '/me', 'GET' );

					// Logged in, now add logged in content.
					$html .= $this->toplistView->doFacebookLogoutButton( $fb->getLogoutUrl() );

					$html .= $toplist;

					$html .= $this->toplistView->doFacebookComments();
					$html .= $this->toplistView->doFacebookLikeButton();
					$html .= $this->toplistView->doFacebookScript();
				} catch( FacebookApiException $e ) {
					// Not logged in, now add logged out content.
					$html .= $this->toplistView->doFacebookLoginButton( $fb->getLoginUrl() );
					$html .= $toplist;
				}
			} else {
				$html .= $this->toplistView->doFacebookLoginButton( $fb->getLoginUrl() );
				$html .= $toplist;
			}
		}

		return $html;
	}
}
